
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
import flash.utils.Timer;


/**
* @author Russell Weir - Based on the nme example by Lee McColl Sylvester
*/
class Drums extends Sprite
{
	#if flash
	static inline var extension = ".mp3";
	#else
	static inline var extension = ".ogg";
	#end

	var mSoundBassDrum : Sound;
	var mSoundDrums : Sound;
	var mSoundCymbals : Sound;


	static function main() {
		#if (neko || cpp)
			neash.Lib.Init("Drum Test", 375, 322);
			neash.Lib.SetBackgroundColour(0xFFFFFF);
		#end

		new Drums();

		#if (neko || cpp)
			neash.Lib.Run();
		#end
	}

	public function new()
	{
		super( );

		var music = new Sound(new URLRequest("Data/Party_Gu-Jeremy_S-8250_hifi"+extension));
		music.play(0.0, -1);

		var ldr = new Loader();
		ldr.load(new URLRequest("Data/drum_kit.jpg" ));
		addChild(ldr);

		flash.Lib.current.addChild(this);

		mSoundDrums = new Sound(new URLRequest("Data/drum"+extension));
		mSoundCymbals = new Sound(new URLRequest("Data/drums"+extension));
		mSoundBassDrum = new Sound(new URLRequest("Data/bass"+extension));

		flash.Lib.current.stage.addEventListener(MouseEvent.CLICK, onClick);
	}


	function onClick(evt:MouseEvent) {
		var bang = new Bang();
		bang.x = evt.stageX - Math.round(bang.width/2);
		bang.y = evt.stageY - Math.round(bang.height/2);
		addChild(bang);

		if (evt.stageY < 100)
			mSoundCymbals.play(0);
		else if (evt.stageY > 200)
			mSoundBassDrum.play(0);
		else
			mSoundDrums.play(0);
	}
}

class Bang extends Sprite
{
	static var mLdr : Loader;

	var timer : Timer;

	public function new()
	{
		super();

		if( mLdr == null ) {
			mLdr = new Loader();
			mLdr.load(new URLRequest("Data/bang.png"));
			addChild(mLdr);
		}
		else {
			var bmp:Bitmap = cast mLdr.content;
			if (bmp!=null)
			   addChild(new Bitmap(bmp.bitmapData.clone()));
		}

		addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
	}

	function onAddedToStage(_) {
		timer = new Timer(200, 1);
		timer.addEventListener(TimerEvent.TIMER, onTimer);
		timer.start();

	}

	function onTimer(_) {
		if(parent != null) {
			parent.removeChild(this);
		}
		if(timer != null) {
			timer.removeEventListener(TimerEvent.TIMER, onTimer);
			timer = null;
		}
	}
}


